package com.mikhailenko.transportMVC.service.es.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mikhailenko.transportMVC.exeption.es.ESNotFoundException;
import com.mikhailenko.transportMVC.model.es.ESEntity;
import com.mikhailenko.transportMVC.repository.es.ESRepository;
import com.mikhailenko.transportMVC.service.es.ESService;

@Service
public class ESServiceImpl implements ESService{

    @Autowired
    private ESRepository esRepository;
    
    @Override
    @Transactional
    public ESEntity create(ESEntity es) {
        ESEntity createdES = es;
        return esRepository.saveAndFlush(createdES);
    }

    @Override
    @Transactional(rollbackFor=ESNotFoundException.class)
    public ESEntity delete(int id) throws ESNotFoundException {
        ESEntity deletedES = esRepository.findOne(id);
        
        if (deletedES == null){
            throw new ESNotFoundException();
        }
        
        esRepository.delete(id);
        return deletedES;
    }

    @Override
    @Transactional
    public List<ESEntity> findAll() {
        return esRepository.findAll();
    }

    @Override
    public ESEntity update(ESEntity es) throws ESNotFoundException {
        ESEntity updatedES = esRepository.findOne(es.getId());
        
        if (updatedES == null){
            throw new ESNotFoundException();
        }
        
        updatedES.setCountOfLayers(es.getCountOfLayers());
        
        return updatedES;
    }

    @Override
    public ESEntity findById(int id) {
        return esRepository.findOne(id);
    }

}
